<template>
  <basic-container>
    <div class="dialog-content">
      <avue-form ref="editForm" :option="option" v-model="form" @submit="handSaveConfig">
        <template slot-scope="{}" slot="someTip">
          <span class="ml20">备注：自动触发报检时机在参数管理配置</span>
        </template>
        <template slot-scope="{}" slot="ruleControl">
          <span>备注：具体到预警中心设计</span>
        </template>
        <template slot-scope="{}" slot="ruleControl">
          <h3>1. 防漏检验控制<span style="color: #f56c6c; margin-right: 4px">*</span></h3>
          <div class="ml20">
            <el-radio v-model="form.missingInspectControl" :label="1" :disabled="isDisable">
              <el-tooltip content="在预警中心设置若待检单的未处理时长达到设定值时，则会预警消息通知" placement="top">
                <i class="el-tooltip el-icon-info"></i>
              </el-tooltip>
              允许生产，仅预警提示告知
            </el-radio>
            <span>备注：具体到预警中心设计</span>
          </div>
          <div class="mt20 ml20 rules-container">
            <el-radio v-model="form.missingInspectControl" :label="2" size="medium" :disabled="isDisable">
              <el-tooltip
                content="待检单达到设定的漏检时长控制时，若是工单首件，该工单每个生产工序都无法过站并提示； 若是工段首件，则该工段内的每个工序无法过站并提示！"
                placement="top"
              >
                <i class="el-tooltip el-icon-info"></i>
              </el-tooltip>
              不允许生产
            </el-radio>
            <div class="ml20 num-input-contain" v-if="form.missingInspectControl === 2">
              <label><span style="color: #f56c6c; margin-right: 4px">*</span>漏检时长控制(min) : </label>
              <el-input-number
                :class="['num-input', { 'invalid-input': !isValid }]"
                placeholder="请输入漏检时长"
                v-model="form.missingInspectDuration"
                :min="0"
                :disabled="isDisable"
                controls-position="right"
                :precision="0"
                class="input-width"
                @blur="handBlur"
              >
              </el-input-number>
              <span class="invalid-span" v-if="!isValid">请输入漏检时长</span>
            </div>
          </div>
        </template>
        <template slot-scope="{}" slot="nGControl">
          <h3>2. 检验结果为NG控制<span style="color: #f56c6c; margin-right: 4px">*</span></h3>
          <div class="ml20">
            <el-radio v-model="form.resultNgControl" :label="1" :disabled="isDisable">
              <el-tooltip content="在预警中心设置若待检单的未处理时长达到设定值时，则会预警消息通知" placement="top">
                <i class="el-tooltip el-icon-info"></i>
              </el-tooltip>
              允许生产，仅预警提示告知
            </el-radio>
            <span>备注：具体到预警中心设计</span>
          </div>
          <div class="mt20 ml20 rules-container">
            <el-radio v-model="form.resultNgControl" :label="2" size="medium" :disabled="isDisable">
              <el-tooltip
                content="待检单达到设定的漏检时长控制时，若是工单首件，该工单每个生产工序都无法过站并提示； 若是工段首件，则该工段内的每个工序无法过站并提示！"
                placement="top"
              >
                <i class="el-tooltip el-icon-info"></i>
              </el-tooltip>
              不允许生产
            </el-radio>
          </div>
        </template>
        <template slot-scope="{}" slot="nGControl1">
          <h3>3. 检验结果为NG，但不良处理不为让步通过时（即为二次检/返工）控制<span style="color: #f56c6c; margin-right: 4px">*</span></h3>
          <div class="ml20">
            <el-radio v-model="form.resultNgHandingControl" :label="1" :disabled="isDisable">
              <el-tooltip content="在预警中心设置若待检单的未处理时长达到设定值时，则会预警消息通知" placement="top">
                <i class="el-tooltip el-icon-info"></i>
              </el-tooltip>
              允许生产，仅预警提示告知
            </el-radio>
            <span>备注：具体到预警中心设计</span>
          </div>
          <div class="mt20 ml20 rules-container">
            <el-radio v-model="form.resultNgHandingControl" :label="2" size="medium" :disabled="isDisable">
              <el-tooltip
                content="待检单结果为让步通过时，若是工单首件，该工单每个生产工序都无法过站并提示； 若是工段首件，则该工段内的每个工序无法过站并提示！"
                placement="top"
              >
                <i class="el-tooltip el-icon-info"></i>
              </el-tooltip>
              不允许生产
            </el-radio>
          </div>
        </template>

        <template slot-scope="{}" slot="colseControl">
          <h3>3. 检验时长控制<span style="color: #f56c6c; margin-right: 4px">*</span></h3>
        </template>
        <template slot-scope="{}" slot="avueCurd">
          <avue-crud ref="editCrud" v-model="form.data" :option="tableOption" :data="form.qmsInspectionPlanObjectVOList">
            <template slot="menuLeft">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddRows" v-if="!isDisable">新 增</el-button>
              <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport" v-if="!isDisable">导入</el-button>
            </template>
            <template slot-scope="{ row, index }" slot="menu">
              <el-button type="text" size="small" icon="el-icon-delete" :disabled="isDisable" @click="rowDel(row, index)">删除</el-button>
            </template>
          </avue-crud>
        </template>
      </avue-form>
    </div>
    <div class="dialog-footer">
      <el-button size="small" type="primary" icon="el-icon-check" @click="handleEditSubmit" v-if="!isDisable">保存</el-button>
      <el-button size="small" icon="el-icon-delete" @click="handleEditReset">取消</el-button>
    </div>
    <importDialogComp
      title="适用对象导入"
      url="/api/mes-product/qms-inspection-planconfig/import-fai-plan-object"
      export-name="适用对象导入模板.xlsx"
      :form-data="fromData"
      :is-form-data-json="true"
      :visible.sync="showImportDialog"
      @submit="codeClose"
    ></importDialogComp>
    <global-modal-template ref="commonModalTemplate" :visibile.sync="selectDialogVisiable" :option="diologOption" @getSelectedRows="getSelectedRows" :key="key" @newKey="newKey">
    </global-modal-template>
  </basic-container>
</template>

<script>
import { guid } from '@/util/helpers';
import importDialogComp from '@/components/dialog/import';
import { getPlanCode, getPlanConfigDetail, savePlanConfig } from '@/api/quality/palnConfig';
// import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
export default {
  name: 'editPlanConfig',
  components: {
    importDialogComp,
    GlobalModalTemplate
  },
  props: {
    type: {
      type: String,
      default: '编辑'
    },
    id: {
      type: String,
      default: ''
    }
  },
  watch: {},
  async mounted() {
    // const res = await getPlanCode();
    // this.form.planNo = res.data.data || '';
    if (this.id) {
      this.getDetail();
    }
  },
  data() {
    return {
      selectDialogVisiable: false,
      showImportDialog: false,
      isValid: true,
      key: new Date().getTime(),
      diologOption: {},
      option: {
        searchShow: true,
        searchMenuSpan: 6,
        menuPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        group: [
          {
            label: '基础信息',
            prop: 'equipmentInfo',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '计划名称',
                prop: 'planName',
                span: 8,
                rules: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
                control: (val, form) => {
                  return {
                    planName: { disabled: this.isDisable }
                  };
                }
              },
              {
                label: '计划编码',
                prop: 'planNo',
                disabled: true,
                placeholder: '系统自动生成',
                span: 8
              },
              {
                label: '检验类型',
                prop: 'planType',
                value: '首件检验',
                disabled: true,
                span: 8
              }
            ]
          },
          {
            label: '报检方式',
            prop: 'equipmentInfo1',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '计划类型',
                prop: 'inspectSubType',
                span: 8,
                labelTip: '具体到预警中心设计',
                type: 'select',
                dicUrl: '/api/blade-system/dict/dictionary?code=inspect_sub_type',
                rules: [{ required: true, message: '请选择计划类型', trigger: 'change' }],
                props: {
                  label: 'dictValue',
                  value: 'dictKey'
                },
                change: ({ value }) => {
                  const column = this.findObject(this.tableOption.column, 'sectionName');
                  if (value === 'WORKORDER') {
                    column.hide = true;
                  } else {
                    column.hide = false;
                  }
                  this.$refs.editCrud.refreshTable();
                },
                control: (val, form) => {
                  return {
                    inspectSubType: { disabled: this.isDisable }
                  };
                }
              },
              {
                label: '报检方式',
                prop: 'sendExamineType',
                dicData: [
                  { label: '自动', value: 'AUTO' },
                  { label: '手动', value: 'MANUAL' }
                ],
                multiple: true,
                span: 8,
                labelTip: '选择手动或自动后，则表示生成的待检单会受防呆规则内容的受控',
                type: 'select',
                rules: [{ required: true, message: '请选择报检方式', trigger: 'change' }],
                control: (val, form) => {
                  return {
                    sendExamineType: { disabled: this.isDisable }
                  };
                }
              },
              {
                labelWidth: 0,
                prop: 'someTip',
                span: 8,
                formslot: true
              }
            ]
          },
          {
            label: '异常处理流程设置',
            prop: 'equipmentInfo3',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '检验结果为NG，需进行不良处理',
                prop: 'resultNgIsHandingControl',
                type: 'radio',
                labelWidth: 220,
                span: 24,
                value: 1,
                control: (val, form) => {
                  return {
                    resultNgIsHandingControl: { disabled: this.isDisable }
                  };
                },
                dicData: [
                  {
                    label: '是',
                    value: 1
                  },
                  {
                    label: '否',
                    value: 2
                  }
                ]
              }
            ]
          },
          {
            label: '防呆规则',
            prop: 'equipmentInfo2',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                prop: 'ruleControl',
                labelWidth: 0,
                span: 24,
                formslot: true
              },
              {
                prop: 'nGControl',
                labelWidth: 0,
                span: 24,
                formslot: true
              },
              {
                prop: 'nGControl1',
                labelWidth: 0,
                span: 24,
                formslot: true
              }
            ]
          },
          {
            label: '关闭控制',
            prop: 'equipmentInfo2',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                prop: 'colseControl',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              },
              {
                label: '未检时间(min)',
                type: 'number',
                min: 0,
                precision: 0,
                prop: 'closeInspectDuration',
                labelWidth: 150,
                span: 6,
                rules: [{ required: true, message: '请输入未检时间', trigger: 'blur' }],
                control: (val, form) => {
                  return {
                    closeInspectDuration: { disabled: this.isDisable }
                  };
                }
              }
            ]
          },
          {
            label: `适用对象`,
            prop: 'equipmentInfo4',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                prop: 'avueCurd',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              }
            ]
          }
        ]
      },
      form: {
        planNo: '',
        // missingInspectControl: 1,
        // resultNgControl: 1,
        qmsInspectionPlanObjectVOList: []
      },
      tableOption: {
        height: '400px',
        calcHeight: 30,
        tip: false,
        searchShow: false,
        filterBtn: false,
        refreshBtn: false,
        columnBtn: false,
        border: true,
        index: true,
        indexLabel: '序号',
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        addBtn: false,
        labelWidth: 130,
        selection: true,
        highlightCurrentRow: true, // 选中高亮
        dialogClickModal: false,
        searchMenuPosition: 'right',
        searchSpan: 6,
        column: [
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '生产工段',
            prop: 'sectionName',
            hide: true
          }
        ]
      }
    };
  },
  computed: {
    isDisable() {
      return this.type === 'view';
    },
    fromData() {
      return { inspectSubType: this.form.inspectSubType, inspectType: 'FAI' };
    }
  },
  methods: {
    newKey() {
      this.key = new Date().getTime();
    },
    async getDetail() {
      try {
        const res = await getPlanConfigDetail({ id: this.id });
        const data = res.data.data;
        const options = JSON.parse(data.options);
        delete data.options;
        const sendExamineType = data.sendExamineType ? data.sendExamineType.split(',') : [];
        this.form = {
          ...data,
          ...options,
          sendExamineType
        };
      } catch (e) {
        console.warn(e);
      }
    },
    handleEditReset() {
      this.$router.go(-1);
      // this.$refs.editForm.resetForm();
      // this.$emit('update:visible', false);
      // this.$emit('closeDialog');
    },
    async handleEditSubmit() {
      if (this.form.missingInspectControl === 2 && !this.form.missingInspectDuration) {
        this.isValid = false;
        return;
      }
      this.$refs.editForm.submit();
    },
    async handSaveConfig(form, done) {
      if (!this.isValid) {
        done();
        return;
      }
      if ((this.form.missingInspectDuration || 0) > this.form.closeInspectDuration) {
        this.$message.error('未检时长要大于漏检时长控制');
        done();
        return;
      }

      if (!this.form.missingInspectControl) {
        this.$message.error('请选择防漏检验控制');
        done();
        return;
      }
      if (!this.form.resultNgControl) {
        this.$message.error('请选择检验结果为NG时控制');
        done();
        return;
      }
      if (!this.form.resultNgHandingControl) {
        this.$message.error('检验结果为NG，但不良处理不为让步通过时（即为二次检/返工）控制');
        done();
        return;
      }
      if (!this.form.qmsInspectionPlanObjectVOList || !this.form.qmsInspectionPlanObjectVOList.length) {
        this.$message.error('请选择适用对象');
        done();
        return;
      }
      const groupByPartNo = this._groupBy(this.form.qmsInspectionPlanObjectVOList, 'partNo');
      const isRepeat = Object.keys(groupByPartNo).some((key) => groupByPartNo[key].length > 1);
      if (isRepeat) {
        this.$message.error('适用对象中存在重复的适用对象,请检查后提交');
        done();
        return;
      }
      const formData = this.filterEmptyValues(this._cloneDeep(this.form));
      const options = {
        missingInspectControl: formData.missingInspectControl,
        missingInspectDuration: formData.missingInspectDuration,
        resultNgControl: formData.resultNgControl,
        resultNgHandingControl: formData.resultNgHandingControl,
        closeInspectDuration: formData.closeInspectDuration,
        resultNgIsHandingControl: formData.resultNgIsHandingControl
      };
      const params = {
        id: formData.id,
        options: JSON.stringify(options),
        inspectType: 'FAI',
        inspectSubType: formData.inspectSubType,
        planNo: formData.planNo,
        planName: formData.planName,
        sendExamineType: formData.sendExamineType.join(','),
        remark: '',
        qmsInspectionPlanObjectVOList: formData.qmsInspectionPlanObjectVOList
      };
      try {
        const res = await savePlanConfig(params);
        this.$message.success('保存成功');
        // this.$refs.editForm.resetForm();
        this.$router.push({
          path: `/quality/refactor/planConfig`
        });
      } catch (e) {
        console.log(e);
      } finally {
        done();
      }
    },
    handleImport() {
      if (!this.form.inspectSubType) {
        this.$message.warning('请选择计划类型');
        return;
      }
      this.showImportDialog = true;
    },
    getSelectedRows(rowData) {
      this.form.qmsInspectionPlanObjectVOList.push(...rowData);
    },

    handleAddRows() {
      if (!this.form.inspectSubType) {
        this.$message.warning('请选择计划类型');
        return;
      }
      let url;
      let column = [
        {
          label: '物料类别',
          prop: 'categoryName'
        },
        {
          label: '物料编码',
          prop: 'partNo',
          search: true
        },
        {
          label: '物料名称',
          prop: 'partName',
          search: true
        },
        {
          label: '生产工段',
          prop: 'sectionName',
          search: true
        }
      ];
      if (this.form.inspectSubType === 'WORKORDER') {
        url = '/api/mes-admin/partmaster/query-page-qms-unused-part-master?inspectType=FAI';
        column.pop();
      } else {
        url = '/api/mes-admin/partmaster/query-page-qms-unused-part-master-by-section?inspectType=FAI';
      }
      this.diologOption = {
        url,
        isPage: true,
        noPageParams: false,
        modalTitle: '选择物料编码',
        rowSelectionType: 'multiple',
        columnDefs: column,
        rowKey: 'partNo',
        index: false,
        selectable: (row, index) => {
          return !this.form.qmsInspectionPlanObjectVOList.map((item) => item.partNo).includes(row['partNo']);
        },
        selectionArray: this.form.qmsInspectionPlanObjectVOList.map((item) => item.partNo) || [],
        isToggleSelection: true,
        filterKey: 'partNo'
      };
      this.selectDialogVisiable = true;
    },
    codeClose(value, data) {
      if (value) {
        const qmsInspectionPlanObjectVOList = this.form.qmsInspectionPlanObjectVOList || [];
        qmsInspectionPlanObjectVOList.push(...data);
        this.$set(this.form, 'qmsInspectionPlanObjectVOList', qmsInspectionPlanObjectVOList);
      }
    },
    handBlur() {
      this.isValid = !(this.form.missingInspectDuration === 0 || !this.form.missingInspectDuration);
    },
    rowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.qmsInspectionPlanObjectVOList.splice(index, 1);
      });
    },
    /**
     * 更新编码
     */
    filterEmptyValues(obj) {
      for (let key in obj) {
        if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
          delete obj[key];
        }
      }
      return obj;
    }
  }
};
</script>

<style scoped lang="scss">
.dialog-content {
  height: calc(100vh - 275px);
  overflow-y: scroll;
  h3 {
    margin: 0;
    font-size: 15px;
  }
  .mt20 {
    margin-top: 20px;
  }
  .ml20 {
    margin-left: 20px;
  }
  .rules-container {
    display: flex;
    align-items: center;
    height: 32px;
  }
  .num-input-contain {
    label {
      position: relative;
    }
    color: #606266;
  }
  .input-width {
    width: 300px;
  }
  .invalid-input {
    ::v-deep .el-input__inner {
      border: 1px solid #f56c6c;
    }
  }
  .invalid-span {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    position: relative;
    top: 25px;
    left: -300px;
  }
}
.dialog-footer {
  height: 52px;
  text-align: right;
  padding: 20px;
}

is-disabled {
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    transition: 1s;
    z-index: 1;
    cursor: not-allowed;
  }
}
</style>
